/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxline.converter;

import br.com.foxline.service.AutocompleteService;
import br.com.foxline.service.CustomerService;
import com.google.common.base.Strings;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

/**
 *
 * @author luciano
 */
@ManagedBean(name = "autocompleteconverter")
@SessionScoped
public class AutocompleteConverter implements Converter {

    @EJB
    private AutocompleteService autocompleteService;

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (value == null || value.equals("null")) {
            return null;
        }
        Class klass;
        if (component.getAttributes().get("className") != null) {
            klass = (Class) component.getAttributes().get("className");
        } else {
            Object object = component.getAttributes().get("value");
            if (object == null) {
                return null;
            } else {
                klass = component.getAttributes().get("value").getClass();
            }
        }
        return autocompleteService.find(klass, Long.parseLong(value));
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        Field field = getIdFromObject(value);
        if (field == null) {
            return null;
        }
        field.setAccessible(true);
        Long id = new Long("0");
        try {
            id = (Long) field.get(value);
        } catch (IllegalArgumentException ex) {
            Logger.getLogger(AutocompleteConverter.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(AutocompleteConverter.class.getName()).log(Level.SEVERE, null, ex);
        }
        field.setAccessible(false);
        return "" + id;
    }

    public Field getIdFromObject(Object o) {
        Field[] fields = o.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.getName().equals("id")) {
                return field;
            }
        }
        return null;
    }
}
